package com.sparrows.pirates.model;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;

public class CannonBall {
	
	private TextureRegion texture;
	private Vector2 position, velocity;
	private float speed; //How fast to fire the cannonball
	private float range; //How far the cannon can go until hitting the ground
	private float distanceTravelled;
	
	//When a cannonball hits the ground, it will stop and fade a bit to appear sunken in the water/sand
	private boolean hitGround, needsDestroying;
	private float hitTimer = 0;

	public CannonBall(TextureRegion texture, Vector2 pos, float fireSpeed, float range, float fireAngle){
		this.texture = texture;
		this.position = pos;
		this.speed = fireSpeed;
		//Adjust range for pixel resolution
		this.range = range*10;
		this.distanceTravelled = 0;
		this.velocity = new Vector2((float) (Math.cos(Math.toRadians(fireAngle))*speed), (float) Math.sin(Math.toRadians(fireAngle))*speed);
	
		this.hitGround = false;
		this.hitTimer = 0;
		this.needsDestroying = false;
	}
	
	public void update(float dt){
		this.distanceTravelled += this.velocity.x + this.velocity.y;
		
		if (this.distanceTravelled >= this.range){
			this.hitGround = true;
			this.hitTimer += 0.1f;
			if (this.hitTimer > 1) {
				this.hitTimer = 1f;
				this.needsDestroying = true;
			}
		} else {
			this.position.x += this.velocity.x;
			this.position.y += this.velocity.y;
		}

	}

	public void draw(SpriteBatch batch){
		if (this.hitGround){
			batch.setColor(0.5f, 0.5f, 0.5f, 1f - this.hitTimer);
		} else {
			batch.setColor(1f, 1f, 1f, 1f);
		}
		batch.draw(texture, position.x - texture.getRegionWidth()/2, position.y - texture.getRegionHeight()/2 ,
				texture.getRegionWidth()/2, texture.getRegionHeight()/2,
				texture.getRegionWidth(), texture.getRegionHeight(), 1, 1, 0);
	}
	
	public boolean needsDestroying(){
		return this.needsDestroying;
	}
}
